package com.weaver.qfengx.servlet.request;

import com.weaver.qfengx.IOUtils;
import com.weaver.qfengx.StringUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.Optional;

public class RequestHelper {

    public static String paramStr(HttpServletRequest request, String param) throws FileUploadException, IOException {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> files = upload.parseRequest(request);
        Optional<FileItem> op = files.stream().filter(x -> StringUtils.equals(x.getFieldName(), param)).findFirst();
        if (op.isPresent()) {
            return IOUtils.string(op.get().getInputStream());
        } else {
            return "";
        }
    }

    public static FileItem paramItem(HttpServletRequest request, String param) throws FileUploadException, IOException {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> files = upload.parseRequest(request);
        Optional<FileItem> op = files.stream().filter(x -> StringUtils.equals(x.getFieldName(), param)).findFirst();
        return op.orElse(null);
    }
}
